package cn.com.anypay.manager.service.impl;

import cn.com.anypay.manager.service.SmsService;
import cn.com.anysdk.sms.api.SmsRequest;
import cn.com.anysdk.sms.api.SmsResponse;
import cn.com.anysdk.sms.config.MockSmsConfig;
import cn.com.anysdk.sms.factory.SmsServiceFactory;
import cn.com.anysdk.sms.api.ISmsService;
import cn.com.anysdk.sms.api.ISmsConfig;
import cn.com.anysdk.sms.config.AliyunSmsConfig;
import cn.com.anysdk.sms.exception.SmsException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Service
public class SmsServiceImpl implements SmsService {



    private ISmsService currentService;
    private ISmsConfig currentConfig;

    @Override
    public String switchProvider(Map<String, Object> config) {
        ISmsConfig smsConfig = createConfigFromMap(config);
        currentService = SmsServiceFactory.createService(smsConfig);
        currentConfig = smsConfig;
        return "SMS Provider switched to: " + smsConfig.getProviderType();
    }


    @Override
    public Map<String, Object> sendSms(String phone, String templateParams) {
        if (currentService == null) {
            throw new SmsException("SMS服务未初始化，请先配置服务商");
        }

        try {
            String templateId = currentConfig.getDefaultTemplateId();
            if (templateId == null || templateId.isEmpty()) {
                throw new SmsException("短信模板代码未配置");
            }

            String signName = currentConfig.getSignName();
            if (signName == null || signName.isEmpty()) {
                throw new SmsException("短信签名未配置");
            }

            log.info("准备发送短信 - 手机号: {}, 签名: {}, 模板: {}, 参数: {}", phone, signName, templateId, templateParams);

            Map<String, String> params = new HashMap<>();
            if (templateParams != null && !templateParams.isEmpty()) {
                try {
                    ObjectMapper mapper = new ObjectMapper();
                    params = mapper.readValue(templateParams, new TypeReference<Map<String, String>>() {});
                } catch (Exception e) {
                    log.warn("解析模板参数失败: {}", e.getMessage());
                }
            }

            SmsRequest request = SmsRequest.builder()
                    .phoneNumber(phone)
                    .templateId(templateId)
                    .signName(signName)
                    .templateParams(params)
                    .build();
            
            log.info("发送短信请求参数: {}", request);
            SmsResponse response = currentService.send(request);
            log.info("短信发送响应: {}", response);

            Map<String, Object> result = new HashMap<>();
            result.put("success", response != null && response.isSuccess());
            result.put("messageId", response != null ? response.getMessageId() : null);
            result.put("phone", phone);
            result.put("templateId", templateId);
            result.put("templateParams", templateParams);
            result.put("sendTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            result.put("response", response);
            
            if (response != null) {
                log.info("短信发送结果 - 成功: {}, 消息ID: {}", 
                    response.isSuccess(),
                    response.getMessageId()
                );
            }

            return result;
        } catch (Exception e) {
            log.error("发送短信失败", e);
            throw new SmsException("发送短信失败: " + e.getMessage(), e);
        }
    }

    @Override
    public Map<String, Object> getCurrentConfig() throws SmsException {
        if (currentConfig == null) {
            throw new SmsException("SMS服务未初始化，请先配置服务商");
        }

        Map<String, Object> config = new HashMap<>();
        config.put("type", currentConfig.getProviderType());
        config.put("accessKeyId", currentConfig.getAccessKeyId());
        config.put("accessKeySecret", currentConfig.getAccessKeySecret());
        config.put("signName", currentConfig.getSignName());
        config.put("templateId", currentConfig.getDefaultTemplateId());
        return config;
    }

    private ISmsConfig createConfigFromMap(Map<String, Object> map) {
        String provider = (String) map.get("type");
        if (provider == null) {
            throw new SmsException("Missing provider type");
        }

        return switch (provider.toLowerCase()) {
            case "aliyun" -> {
                String accessKeyId = (String) map.get("accessKeyId");
                String accessKeySecret = (String) map.get("accessKeySecret");
                String signName = (String) map.get("signName");
                String templateId = (String) map.get("templateId");
                if (accessKeyId == null || accessKeyId.isEmpty() ||
                    accessKeySecret == null || accessKeySecret.isEmpty() ||
                    signName == null || signName.isEmpty() ||
                    templateId == null || templateId.isEmpty()) {
                    throw new SmsException("SMS配置缺少必要参数");
                }
                yield AliyunSmsConfig.builder()
                        .accessKeyId(accessKeyId)
                        .accessKeySecret(accessKeySecret)
                        .signName(signName)
                        .defaultTemplateId(templateId)
                        .build();
            }
            case "mock" -> {
                String accessKeyId = (String) map.get("accessKeyId");
                String accessKeySecret = (String) map.get("accessKeySecret");
                String signName = (String) map.get("signName");
                String templateId = (String) map.get("templateId");
                if (accessKeyId == null || accessKeyId.isEmpty() ||
                    accessKeySecret == null || accessKeySecret.isEmpty() ||
                    signName == null || signName.isEmpty() ||
                    templateId == null || templateId.isEmpty()) {
                    throw new SmsException("SMS配置缺少必要参数");
                }
                MockSmsConfig config = new MockSmsConfig();
                config.setAccessKeyId(accessKeyId);
                config.setAccessKeySecret(accessKeySecret);
                config.setSignName(signName);
                config.setDefaultTemplateId(templateId);
                yield config;
            }
            default -> throw new SmsException("Unsupported provider: " + provider);
        };
    }


}
